<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Admin;
use app\model\AdminToken;
use Firebase\JWT\JWT;
use think\facade\Validate;
use think\Request;
use app\model\Admin as AdminModel;
use think\Response;

class Login
{
    /**
     * 登录接口
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        //获取参数
        $data = $request->param();

        //验证参数
        $validate = Validate::rule([
            'account' => 'require|length:5,25',
            'password' => 'require|length:6,10'
        ]);
        if(!$validate->check($data)) return $this->create([],$validate->getError(),400);
        //验证账号和密码
        $result = AdminModel::where(['account'=>$data['account'],'password'=>md5(sha1($data['password']))])
            ->withoutField('password')
            ->find();

        if( !$result ){
            return $this->create([],'登录失败，账号或密码错误！',401);
        }

        if( !$result['status'] ) return $this->create([],'已被禁用，请联系管理员！',403);

        //生成token
        $create_time = time();
        $expire_time = $create_time + 3600*24*7;

        $token = $this->createToken(['admin_id'=>$result['id'],'account'=>$result['account']],$expire_time,$create_time);

        //持久化token到数据表
        AdminToken::create([
                'admin_id'=>$result['id'],
                'token'=>$token,
                'expire_time'=>$expire_time,
                'create_time'=>$create_time
            ]
            ,[],true);

        $result->last_login_time = $create_time;
        $result->isAutoWriteTimestamp(false)->save();

        $result['token'] = $token;
        return $this->create($result,'登录成功');

    }

    //退出接口
    public function logout(Request $request){
        //获取参数
        $data = $request->param();
        $check_re = Validate::rule(['token'=>'require|min:200'])->check($data);
        //
        if($check_re) {
            //删除对应token
            AdminToken::where(['token' => $data['token']])->delete();
        }
        return $this->create([],'退出成功');
    }

    private function create($data, string $msg = '', int $code = 200, string $type = 'json'){
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return Response::create($result,$type);
    }

    private function createToken($item,$expire_time,$create_time)
    {
        $secret = config('app.secret');      //密匙
        $payload = [
            'iss'=>'sol',                //签发人(官方字段:非必需)
            'exp'=>$expire_time,     //过期时间(官方字段:非必需)
            'aud'=>'admin',              //受众(官方字段:非必需)
            'nbf'=>$create_time,               //生效时间(官方字段:非必需)
            'iat'=>$create_time,               //签发时间(官方字段:非必需)
            'data'=>$item              //自定义字段
        ];
        $token = JWT::encode($payload,$secret,config('app.token_sign'));
        return $token;
    }
}
